﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.IO;
using System.Xml.Linq;

namespace VersionBuilder
{
	public class UpdateVersion : Task
	{
		[Required]
		public ITaskItem Version { get; set; }

		[Required]
		public ITaskItem VsixManifest { get; set; }

		[Required]
		public ITaskItem Nuspec { get; set; }

		public override bool Execute()
		{
			var version = new Version(this.Version.ItemSpec);
			var vsixManifestPath = this.VsixManifest.GetMetadata("FullPath");
			var nuspecPath = this.Nuspec.GetMetadata("FullPath");

			foreach (var item in new[] { 
				Tuple.Create(vsixManifestPath, new Action<XDocument, Version>(UpdateVsixManifest)), 
				Tuple.Create(nuspecPath, new Action<XDocument, Version>(UpdateNuspec)) })
			{
				var xml = File.ReadAllText(item.Item1);
				var document = XDocument.Parse(xml);
				item.Item2(document, version);
				using (var stream = File.OpenWrite(item.Item1))
					document.Save(stream);
			}

			return true;
		}

		private static void UpdateVsixManifest(XDocument document, Version version)
		{
			var root = document.Root;
			var ns = root.Attribute("xmlns").Value;
			var element = root.Element(XName.Get("Identifier", ns)).Element(XName.Get("Version", ns));
			element.Value = version.ToString();
		}

		private static void UpdateNuspec(XDocument document, Version version)
		{
			var root = document.Root;
			var ns = root.Attribute("xmlns").Value;
			var element = root.Element(XName.Get("metadata", ns)).Element(XName.Get("version", ns));
			element.Value = version.ToString();
		}
	}
}
